/*
-----------------------------------------------------------------------------
This source file is part of as4game
(ActionScript For Game Engine)
For the latest info, see http://as4game.googlecode.com

Copyright (c) 2000-2011 Hproof Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
package
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Matrix3D;
	import flash.geom.Rectangle;
	import flash.geom.Vector3D;
	import flash.ui.Keyboard;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;
	
	import org.as4game.common.disp.FloatText;
	import org.as4game.common.utils.Fps;
	import org.as4game.common.utils.KeyboardState;
	import org.as4game.render3d.Render3D;
	import org.as4game.resource.anim.Animation;
	import org.as4game.resource.anim.AnimationState;
	import org.as4game.resource.anim.AnimationStateSet;
	import org.as4game.resource.bitmap.Material;
	import org.as4game.resource.manager.ResourceManager;
	import org.as4game.resource.mesh.Mesh;
	import org.as4game.resource.skeleton.Bone;
	import org.as4game.resource.skeleton.Skeleton;
	import org.as4game.scene3d.Camera;
	import org.as4game.scene3d.Entity;
	import org.as4game.scene3d.Node;
	import org.as4game.scene3d.Plane;
	import org.as4game.scene3d.Scene;
	import org.as4game.scene3d.SceneNode;
	import org.aswing.tree.PathPlaceHolder;
	import org.ext.loader.ogre.MeshSerializer;
	import org.ext.loader.ogre.OgreLoader;
	import org.ext.loader.ogre.SkeletonSerializer;
	import org.osmf.layout.ScaleMode;
	
	/**
	 * TestRender25D
	 */
	public class TestRender25D extends Sprite
	{
		static private const TOUSHI:Boolean = false; 
		
		private var _fps:Fps;
		private var _info:FloatText;
		private var _render:Render3D;
		private var _scene:Scene;
		private var _camera:Camera;
		private var _keyState:KeyboardState;
		private var _entites:Vector.<Entity>
		
		//
		public function TestRender25D(){
			
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			
			initResource( next);
			
			function next():void{
				_render = new Render3D;
				_render.create( stage, initScene );
			}
		}
		
		// 初始化场景
		private function initScene( render3d:Render3D ):void{
			_fps = new Fps;
			addChild( _info = new FloatText );
			
			_scene = new Scene;
			
			_camera = new Camera;
			_scene.root.addChild( new SceneNode(null, _camera ) );
			_camera.sceneNode.mLocalMatrix.appendTranslation(0, -10, 10);
			_camera.sceneNode.mLocalMatrix.prependRotation(45, Vector3D.X_AXIS );
			_camera.sceneNode.setLocalChanged();
			
			_keyState = new KeyboardState( stage );
			
			_entites = new Vector.<Entity>;
			for(var loop:int=0; loop<1; loop++){
				for(var i:int=0; i<20; i++){
					var x:int = i * 2;
					var z:int = -loop * 2;
					
					var e:Entity = createEntity( null, ID_HERO );
					_entites.push( e );
					var scale:Number = (1 / e.mMesh.mBoundRadius);
					_scene.root.addChild( new SceneNode( null, e ) );
					e.sceneNode.mLocalMatrix.appendScale(scale, -scale, scale);
					e.sceneNode.mLocalMatrix.appendRotation( 360/8*loop, Vector3D.Y_AXIS );
					e.sceneNode.mLocalMatrix.appendTranslation(x, 0, z);
					e.sceneNode.setLocalChanged();
					
					if( e.hasSkeleton() ){
						var aniList:Vector.<Animation> = e.mSkeletonInstance.mSkeleton.mAnimationsList;
						var ani:Animation = aniList[ i % aniList.length ];
						e.getAnimationState( ani.mName ).setEnabled( true );
						if( i >= aniList.length ) break;
					}
					else break;
				}
			}
			
			// start render
			stage.addEventListener( Event.ENTER_FRAME, onEnterFrame );
			stage.addEventListener( MouseEvent.MOUSE_DOWN, onMouseEvent);
			stage.addEventListener( MouseEvent.MOUSE_MOVE, onMouseEvent);
			stage.addEventListener( MouseEvent.MOUSE_WHEEL, onMouseEvent);
			stage.addEventListener( Event.RESIZE, onResize );
			onResize( null );
		}
		
		private function onResize(e:Event):void{
			_render.viewport = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight );
			_render.context3D.configureBackBuffer( stage.stageWidth, stage.stageHeight, 1, true);
			_camera.aspect = stage.stageWidth / stage.stageHeight;
		} 
		
		private var _mousex:int, _mousey:int;
		private function onMouseEvent(e:MouseEvent):void{
			switch( e.type ){
				case MouseEvent.MOUSE_DOWN:
					_mousex = e.stageX;
					_mousey = e.stageY;
					break;
				case MouseEvent.MOUSE_MOVE:
					if( e.buttonDown ){
						var dx:int = e.stageX - _mousex;
						var dy:int = e.stageY - _mousey;
						_mousex = e.stageX;
						_mousey = e.stageY;
						if( TOUSHI ){
							_camera.sceneNode.mLocalMatrix.prependRotation( dx , Vector3D.Y_AXIS );
							_camera.sceneNode.mLocalMatrix.prependRotation( -dy , Vector3D.X_AXIS);
						}
						else{
							_camera.sceneNode.mLocalMatrix.appendTranslation( dx, 0, dy);
						}
						_camera.sceneNode.setLocalChanged();
					}
					break;
				case MouseEvent.MOUSE_WHEEL:
					if( TOUSHI ){
						_camera.sceneNode.mLocalMatrix.prependTranslation( 0, 0, -e.delta );
						_camera.sceneNode.setLocalChanged();
					}
					break;
			}
		}
		
		private function onEnterFrame(e:Event):void{
			_fps.frameStart();
			_fps.updateStart();
			
			var m:Matrix3D;
			if( TOUSHI ){
				m = _keyState.getMoveMatrix( 0.2, 12);
				_camera.sceneNode.mLocalMatrix.prepend( m );
			}
			else{
				m = _keyState.getTranslateMatrix( 0.2 );
				_camera.sceneNode.mLocalMatrix.append( m );
			}
			_camera.sceneNode.setLocalChanged();
			
			var time_pass:Number  = _fps.time_pass / 1000;
			for each(var ent:Entity in _entites ){
				ent.addAnimationTime( time_pass );
			}
			
			var passes:Array = _render.preRender( _scene );
			
			var vp:Matrix3D = _camera.sceneNode.mWorldMatrix.clone();
			vp.invert();
			var p:Matrix3D;
			if( TOUSHI ){
				p = _camera.projection;
			}
			else{
				p = Camera.makeRectangularProjection( -5, 5, -5, 5, 0, -100);
			}
			vp.append( p );
			
			_fps.renderStart();
			_render.render( _scene, vp, passes );
			
			_fps.frameEnd();
			
			_info.text = [
				"[" + _render.context3D.driverInfo.split(" ")[0] + "]", 
				"FPS: " + _fps.fps,
				"TRI: " + _render.num_triangle, 
				"PASS: " + _render.num_pass, 
				"FRAME: " + _fps.frameRatio+ "%", 
				"UPDATE: " + _fps.updateRatio+ "%",  
				"RENDER: " + _fps.renderRatio + "%",
			].join("  ");
		}
		
		// ================================================================================
		// resource
		static private const pathnames:Array = [
//			["?cat/", "cat"],
//			["?dog/", "dog"],
//			["F:/Game/火炬之光/Pak/media/models/Alchemist/", "Alchemist"],
//			["F:/Game/火炬之光/Pak/media/models/Bosses/Alric/", "Alric"],
//			["F:/Game/火炬之光/Pak/media/models/Zombie/", "Zombie"],	// 小怪物
//			["F:/Game/火炬之光/Pak/media/models/barrel/", "barrel"],	// 木桶
//			["F:/Game/火炬之光/Pak/media/models/barrelexplosive/", "barrel"],	// 木桶, 红色
//			["F:/Game/火炬之光/Pak/media/models/box/", "box"],	// 立方体
//			["F:/Game/火炬之光/Pak/media/models/Burrower/", "Burrower"],	// 小乌龟
//			["F:/Game/火炬之光/Pak/media/models/cat/", "cat"],	// 宠物猫
//			["F:/Game/火炬之光/Pak/media/models/dog/", "dog"],	// 宠物狗
//			["F:/Game/火炬之光/Pak/media/models/gel/", "gel"],	// 水珠
//			["F:/Game/火炬之光/Pak/media/models/ghost/", "ghost"],	// 幽灵, 但骨骼太多
//			["F:/Game/火炬之光/Pak/media/models/Gobbler/", "Gobbler"],	// 小恐龙
//			["F:/Game/火炬之光/Pak/media/models/Horse/", "Horse"],	// 马
//			["E:/TDDOWNLOAD/3d模型/资源_天龙版/资源_天龙版/资源_天龙版/Client/Media/人物/石人/", "云母石人"],	// 马
			["E:/TDDOWNLOAD/3d模型/资源_天龙版/资源_天龙版/资源_天龙版/Client/Media/人物/美人鱼/", "美人鱼头"],	// 马
			["E:/TDDOWNLOAD/3d模型/资源_天龙版/资源_天龙版/资源_天龙版/Client/Media/人物/美人鱼/", "美人鱼身"],	// 马
		];
		static private const ID_MONSTER:String = "cat";
		static private const ID_HERO:String = "美人鱼";
		
		
		// 初始化资源
		private function initResource( next:Function ):void{
			var path:String = loaderInfo.url;
			path = path.substr( 0, path.lastIndexOf("/")+1 );
			path = path + "res/";
			
			for each(var arr:Array in pathnames ){
				if( String(arr[0]).charAt(0) == "?"){
					arr[0] = path + String(arr[0]).substr(1);
				}
			}
			OgreLoader.loadAll( pathnames, onLoadComplete, "euc-cn" );
			
			//
			function onLoadComplete():void{
				
				// 合并零散的模型
				var m1:Mesh = ResourceManager.getMesh( "美人鱼头.mesh" );
				var m2:Mesh = ResourceManager.getMesh( "美人鱼身.mesh" );
				m2.mergeSubMesh( m1 );
				ResourceManager.setMesh( "美人鱼.mesh", m2 );
				
				next();
			}
		}
		
		// 建立实体
		private function createEntity( name:String, id:String ):Entity{
			var e:Entity = new Entity( name, id + ".mesh" );
			return e;
		}
	}
}